package com.example.kiratest.realize;

import java.io.*;
import java.nio.file.*;
import java.util.*;
//多版本兼容
public class CrossPlatformPythonExecutor {
    
    /**
     * 执行Python脚本获取应用版本号
     */
    public String getAppVersion(String packageName, String lang, String country) {
        try {
            // 1. 准备平台相关的Python环境
            PythonEnvironment env = preparePythonEnvironment();
            
            // 2. 构建执行命令
            String[] command = buildPythonCommand(env, packageName, lang, country);
            
            // 3. 执行命令并返回结果
            return executePythonCommand(command);
            
        } catch (Exception e) {
            System.err.println("执行Python脚本失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 准备Python执行环境
     */
    private PythonEnvironment preparePythonEnvironment() throws IOException {
        boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");
        
        // 如果是Windows，尝试使用打包的python.exe
        if (isWindows) {
            Path pythonExe = extractResourceIfExists("/other/python.exe");
            if (pythonExe != null) {
                return new PythonEnvironment(pythonExe.toString(), "windows");
            }
        }
        
        // 其他情况使用系统Python
        return new PythonEnvironment(findSystemPython(), isWindows ? "windows" : "unix");
    }

    
    /**
     * 构建Python执行命令
     */
    private String[] buildPythonCommand(PythonEnvironment env, String... args) throws IOException {
        List<String> command = new ArrayList<>();
        
        // 添加Python解释器
        command.add(env.pythonPath);
        
        // 添加Python脚本
        if (env.platform.equals("windows")) {
            // Windows使用打包的脚本
            Path scriptPath = extractResource("/other/getVersionChange.py");
            command.add(scriptPath.toString());
        } else {
            // Linux/Mac使用资源目录下的脚本
            Path scriptPath = extractResource("/scripts/get_version.py");
            command.add(scriptPath.toString());
        }
        
        // 添加其他参数
        Collections.addAll(command, args);
        
        return command.toArray(new String[0]);
    }
    
    /**
     * 查找系统Python解释器
     */
    private String findSystemPython() throws IOException {
        String[] commands = System.getProperty("os.name").toLowerCase().contains("win")
                ? new String[]{"python.exe", "python3.exe", "py.exe"}
                : new String[]{"/usr/bin/python3", "/usr/local/bin/python3", "python3", "python"};
        
        for (String cmd : commands) {
            if (checkPythonAvailable(cmd)) {
                return cmd;
            }
        }
        throw new IOException("未找到可用的Python解释器，请确保已安装Python并添加到PATH");
    }
    
    /**
     * 检查Python是否可用
     */
    private boolean checkPythonAvailable(String pythonPath) {
        try {
            Process process = new ProcessBuilder(pythonPath, "--version").start();
            return process.waitFor() == 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 从资源文件提取到临时目录
     */
    private Path extractResource(String resourcePath) throws IOException {
        try (InputStream in = getClass().getResourceAsStream(resourcePath)) {
            if (in == null) {
                throw new IOException("资源文件未找到: " + resourcePath);
            }
            
            Path tempDir = Files.createTempDirectory("python-resources");
            Path targetPath = tempDir.resolve(Paths.get(resourcePath).getFileName());
            Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);
            
            // 设置执行权限(Linux/Mac需要)
            if (!System.getProperty("os.name").toLowerCase().contains("win")) {
                targetPath.toFile().setExecutable(true);
            }
            
            // JVM退出时删除临时文件
            targetPath.toFile().deleteOnExit();
            tempDir.toFile().deleteOnExit();
            
            return targetPath;
        }
    }
    
    /**
     * 尝试提取资源文件，不存在返回null
     */
    private Path extractResourceIfExists(String resourcePath) {
        try {
            return extractResource(resourcePath);
        } catch (IOException e) {
            return null;
        }
    }
    
    /**
     * 执行Python命令并返回结果
     */
    private String executePythonCommand(String[] command) throws IOException, InterruptedException {
        Process proc = Runtime.getRuntime().exec(command);
        
        // 读取输出流
        StringBuilder output = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(proc.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
        }
        
        // 读取错误流
        StringBuilder errorOutput = new StringBuilder();
        try (BufferedReader errorReader = new BufferedReader(
                new InputStreamReader(proc.getErrorStream()))) {
            String line;
            while ((line = errorReader.readLine()) != null) {
                errorOutput.append(line).append("\n");
            }
        }
        
        int exitCode = proc.waitFor();
        
        if (exitCode != 0) {
            throw new IOException(String.format(
                "Python脚本执行失败(退出码:%d)\n错误输出:\n%s", 
                exitCode, errorOutput.toString()));
        }
        
        return output.toString();
    }
    
    /**
     * Python环境描述类
     */
    private static class PythonEnvironment {
        final String pythonPath;
        final String platform; // "windows" or "unix"
        
        PythonEnvironment(String pythonPath, String platform) {
            this.pythonPath = pythonPath;
            this.platform = platform;
        }
    }
}